package com.citsin.atlas.adapter

import android.content.ContentUris
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.citsin.atlas.R
import com.citsin.atlas.bean.Album
import java.io.File

/**
 * citsin
 * 2019-06-04
 */
class AlbumAdapter(private val context: Context) : PagedListAdapter<Album, AlbumAdapter.AlbumItemViewHolder>(diffCallback) {

    private val inflater = LayoutInflater.from(context)
    fun setOnItemClickListener(e: (Int,Album?) -> Unit) {
        this.listener = e
    }
    private var listener: (Int,Album?) -> Unit = {_,_ ->}

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AlbumItemViewHolder {
        return AlbumItemViewHolder(inflater.inflate(R.layout.item_album, parent, false))
    }

    override fun onBindViewHolder(holder: AlbumItemViewHolder, position: Int) {
        val item = getItem(position)
        holder.displayNameView.text = item?.displayName
        holder.itemView.setOnClickListener { listener(position,item) }
        val uri = Uri.fromFile(File(item!!.data))
        Glide.with(context).load(uri).into(holder.imageView)
    }

    inner class AlbumItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
        val imageView:ImageView = itemView.findViewById(R.id.imageView)
        val displayNameView: TextView = itemView.findViewById(R.id.displayNameView)
        val countView:TextView = itemView.findViewById(R.id.countView)
        val arrowRightView:ImageView = itemView.findViewById(R.id.arrowRightView)
    }

    companion object {
        private val diffCallback = object : DiffUtil.ItemCallback<Album>() {
            override fun areItemsTheSame(oldItem: Album, newItem: Album): Boolean {
                return oldItem.id === newItem.id
            }

            override fun areContentsTheSame(oldItem: Album, newItem: Album): Boolean {
                return oldItem == newItem
            }
        }
    }
}
